#include <iostream>
#include <unistd.h>
#include <vector>
#include <pthread.h>
#include <sys/types.h>
#include <ctime>
#include <string>
#include <functional>
#include <stdint.h>
const int gnum = 5;


//结论：线程被分离了，可以被detach，被取消了，可以被detach，获取的返回参数无意义
using func_t = std::function<void()>;

class ThreadData
{
public:
    ThreadData(std::string threadname, const uint64_t &time, func_t func)
        : _threadname(threadname), _time(time), _f(func)
    {
    }

public:
    std::string _threadname;
    uint64_t _time;
    func_t _f;
};

std::string Tohex(pthread_t t)
{
    char buffer[64];
    snprintf(buffer, sizeof(buffer), "0x%lx", t);
    return buffer;
}

void Print()
{
    std::cout << "这是一个打印的任务......" << std::endl;
}

void *threadRountine(void *args)
{
    ThreadData *t = static_cast<ThreadData *>(args);
    int cnt = 10;
    while (1)
    {
        std::cout << t->_threadname << ",create time:" << t->_time << std::endl;
        t->_f();
        sleep(1);
    }
    //pthread_detach(pthread_self());

    //const char *ret = t->_threadname.c_str();
    return (void *)10;
    //pthread_exit((void*)10);
}
int main()
{
    std::vector<pthread_t> threads;
    for (int i = 0; i < gnum; i++)
    {
        char threadname[64];
        snprintf(threadname, sizeof(threadname), "thread-%d", i + 1);
        pthread_t tid;
        ThreadData *td = new ThreadData(threadname, (uint64_t)time(nullptr), Print);
        pthread_create(&tid, nullptr, threadRountine, (void *)td);
        threads.push_back(tid);
        sleep(1);
    }
    pthread_cancel(threads[0]);
    for (auto t : threads)
    {
        void *ret=nullptr;
        int n=pthread_join(t, &ret);
         std::cout << "子线程返回值：" << (int64_t)ret << std::endl;
        std::cout << "回收子线程,n:"<<n<<",ret:" << (int64_t)ret << " ,tid:" << Tohex(t) << "成功！" << std::endl;
    }

    return 0;
}